package openbang.account.web.portal.widget;

import java.util.Date;
import java.util.List;

import openbang.account.service.entity.MsgAsyn;
import openbang.account.service.entity.MsgReceive;
import openbang.account.service.exception.SecurityOBException;
import openbang.account.service.intf.MsgService;
import openbang.account.service.vo.ExceptionEnum;
import openbang.account.service.vo.MsgServiceEnum;
import openbang.account.service.vo.MsgStatusEnum;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 消息显示和操作（新建、回复、删除、存档、刷新、翻页）
 * 消息类型：已存档、未存档
 * 
 * 布局：
 * 按钮栏
 * 消息列表
 * 消息明细（POPUP）-- 没有阅读的,置为已经阅读
 * 
 * @author aibozeng
 *
 */
public class MsgListWidget extends Composite{
	//ROOT Widget
	VerticalPanel vPanelMenu = new VerticalPanel();
	
	//按钮栏
	HorizontalPanel btnPanel = new HorizontalPanel();
	Button replyBtn = new Button("回复");
	Button deleBtn = new Button("删除");
	Button archiveBtn = new Button("存档");
	Button newBtn = new Button("新建");
	Button refreshBtn = new Button("刷新");
	Button newerPageBtn = new Button("<<新页");
	Button orderPageBtn = new Button("旧页>>");
	
	//消息列表
	Grid msgTable = new Grid(1,5);
	//没有数据的提示
	HTML noDataHtml = new HTML("没有消息");
	
	private MsgDetailWidget msgDetailWidget = new MsgDetailWidget(); 

	//数据参数  
	int msgStatus = MsgStatusEnum.HAS_READ.getCode();//收件箱还是存档箱
	int nowPageNo = 1;//当前页码
	int pageCount = 20; //一页记录数,允许用户修改
	
	//当前显示页的消息对象
	List<MsgReceive> pageMsg = null;

	//当前显示消息内容的行号
	//int lineIndex = 0;
	
	/**
	 * 消息控制器,如：写新消息、回复消息  --- 外部控制
	 */
	MsgHandler msgHandler = null;
	
	//本组件控制的发送消息
	DialogBox sendMsgDialogBox = null;
	VerticalPanel sendMailPanel = new VerticalPanel();
	SendMsgWidget sendMsgWidget = null;
	private Button closeButton = new Button("关闭");
	
	public MsgListWidget(){
		this(MsgStatusEnum.HAS_READ.getCode());
	}
	public MsgListWidget(int msgStatus){
		super();
		this.msgStatus = msgStatus;
		initWidget(vPanelMenu);
		vPanelMenu.add(btnPanel);
		vPanelMenu.add(msgTable);
		vPanelMenu.add(noDataHtml);
		noDataHtml.setVisible(false);
		
		//按钮
		btnPanel.add(replyBtn);
		btnPanel.add(deleBtn);
		if(msgStatus == MsgStatusEnum.HAS_READ.getCode()){
		   btnPanel.add(newBtn);
		   btnPanel.add(archiveBtn);
		}
		btnPanel.add(refreshBtn);
		btnPanel.add(newerPageBtn);
		btnPanel.add(orderPageBtn);
		btnPanel.add(new HTML("&nbsp;&nbsp;登录后,系统暂没有实现定时查新消息,请单击<刷新>"));
		newerPageBtn.setEnabled(false);
		orderPageBtn.setEnabled(false);
		//消息表格头
		msgTable.setHTML(0,0,"<b>选择</b>");
		msgTable.setHTML(0,1,"<b>发送人</b>");
		msgTable.setHTML(0,2,"<b>发送日期</b>");
		msgTable.setHTML(0,3,"<b>消息标题</b>");
		msgTable.setHTML(0,4,"<b>状态</b>");
		//由外部调用
		beginToReadData();
		
		refreshBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				refreshBtn.setEnabled(false);
				beginToReadData();
			}
		});
		replyBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				if(pageMsg==null || pageMsg.size()<=0){
					Window.alert("没有消息可以回复,请发消息");
					return;
				}
				int rowNum = msgTable.getRowCount();
				for(int i=1;i<rowNum;i++){
					if(((CheckBox)msgTable.getWidget(i,0)).getValue()){
						if(msgHandler!=null){
							msgHandler.replyMsg(pageMsg.get(i-1).getMsgAsyn());
							return;
						}
						else{
							//使用 Popup
							initSendMsgDialog();
							sendMsgDialogBox.setText("回复消息");
							sendMsgWidget.replyMsg(pageMsg.get(i-1).getMsgAsyn());
							return;
						}
					}
				}
				Window.alert("请选择一个消息进行回复");
			}
		});
		deleBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				Window.alert("未实现");
			}
		});
		archiveBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				Window.alert("未实现");
			}
		});		
/*		newerPageBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				Window.alert("未实现");
			}
		});		
		orderPageBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				Window.alert("未实现");
			}
		});		
*/		newBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				if(msgHandler!=null){
					msgHandler.sendNewMsg();
				}
				else{
					//使用 Popup
					initSendMsgDialog();
					sendMsgDialogBox.setText("创建新消息");
					sendMsgWidget.sendNewMsg();
					return;
				}
			}
		});			
	}
	
	public void beginToReadData(){	
		MsgService.Util.getInstance().getListMsg(msgStatus,nowPageNo, pageCount, new AsyncCallback<List<MsgReceive>>() {
			@Override
			public void onSuccess(List<MsgReceive> result) {				
				endToReadData(result);
			}
			@Override
			public void onFailure(Throwable caught) {
				refreshBtn.setEnabled(true);
				if(caught instanceof SecurityOBException){
					SecurityOBException obe = (SecurityOBException)caught;
					Window.alert( ExceptionEnum.getDesc(obe.getCode()));
				}
				else{
					Window.alert(caught.getMessage());
				}				
			}
		});
	}

	public void endToReadData(List<MsgReceive> msgReceives){
		refreshBtn.setEnabled(true);
		if(msgReceives==null||msgReceives.size()==0){
			noDataHtml.setVisible(true);
			return;
		}
		pageMsg = msgReceives;
		msgTable.resizeRows(pageMsg.size()+1);
		int index = 1;
		for(MsgReceive msgRece : pageMsg){
			MsgAsyn msg = msgRece.getMsgAsyn();			
			msgTable.setWidget(index,0,new CheckBox());
			msgTable.setText(index,1,msg.getSenderEmail());
			msgTable.setText(index,2,DateTimeFormat.getFormat("yyyy-MM-dd HH:mm").format(msg.getSendTime()));
			Hyperlink titleLink = new Hyperlink();
			titleLink.setText(msg.getMsgTitle());
			titleLink.addClickHandler(new ViewMsgClickHandler(index));
			msgTable.setWidget(index,3,titleLink);
			msgTable.setText(index,4,MsgStatusEnum.getDesc(msgRece.getReadStatus()));
			index++;
		}
	}
	
	public class ViewMsgClickHandler implements ClickHandler{		
		int indexLine = 1;//grid 行号  0开始
		public ViewMsgClickHandler(){			
		}
		public ViewMsgClickHandler(int index){	
			this.indexLine = index;
		}
		public void onClick(ClickEvent event) {
			MsgReceive msgR = pageMsg.get(indexLine-1);
			msgDetailWidget.viewMsg(msgR.getMsgAsyn().getMsgBody());
			msgDetailWidget.show();
			msgDetailWidget.center();
			if(msgR.getReadStatus()==MsgStatusEnum.PENDING_READ.getCode()){
				//置为已读
				MsgService.Util.getInstance().doSetReadMsg(msgR.getId(), new AsyncCallback<Integer>() {
					public void onSuccess(Integer result) {
						if(result==MsgServiceEnum.OK.getCode()){
							//更新当前的MsgReceive对象
							MsgReceive msgR = pageMsg.get(indexLine-1);
							msgR.setReadStatus(MsgStatusEnum.HAS_READ.getCode());
							msgR.setReadTime(new Date());
							//更新当前Grid内容
							msgTable.setText(indexLine,4,MsgStatusEnum.HAS_READ.getDesc());
						}
					}
					public void onFailure(Throwable caught) {
						if(caught instanceof SecurityOBException){
							SecurityOBException obe = (SecurityOBException)caught;
							Window.alert( ExceptionEnum.getDesc(obe.getCode()));
						}
						else{
							Window.alert(caught.getMessage());
						}				
					}
				});
			}
		}
	}

	public void initSendMsgDialog(){
		if(sendMsgDialogBox==null){
			sendMsgDialogBox = new DialogBox();
		    sendMsgDialogBox.setPixelSize(600, 400);
			sendMsgWidget = new SendMsgWidget();
			sendMailPanel.add(sendMsgWidget);
			sendMailPanel.add(closeButton);
			sendMsgDialogBox.setTitle("发消息/回消息");
			sendMsgDialogBox.setWidget(sendMailPanel);
		    closeButton.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					sendMsgDialogBox.hide();
				}
			});
		}
		sendMsgDialogBox.center();
		sendMsgDialogBox.show();
	}
	
	public MsgHandler getMsgHandler() {
		return msgHandler;
	}
	public void setMsgHandler(MsgHandler msgHandler) {
		this.msgHandler = msgHandler;
	}
		
}
